///**
// * Created by MBENBEN on 2016/9/20.

var mysql = require('mysql');
var $sql = require('./userSqlMapping');
var $conf = require('../conf/db');
var conn = mysql.createPool($conf.mysql);
var fs = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var path = require('path');

//var mysql = require('easymysql');
//var $sql = require('./userSqlMapping');
//var $conf = require('../conf/db');
//
//var conn = mysql.create({
//    'maxconnections' : 100
//});
//
//conn.addserver($conf.mysql);
//
//conn.on('busy', function (queuesize, maxconnections, which) {
//    console.log('busy')
//    // XXX: write log and monitor it
//});

var jsonWrite = function(res, ret) {
	if(typeof ret === 'undefined') {
		res.json({
			code: '1',
			msg: '参数有误'
		});
	} else {
		res.json(ret);
	}
};

module.exports = {
	addReview: function(req, res, next) {
		var param = req.body;
		conn.getConnection(function(err, conn) {
			conn.query($sql.updateReview, [param.id], function(err, result) {
				//console.log(param,param.number,new Date())
				request('http://127.0.0.1:3000/html/ac'+param.id+'.html', function(error, response, body) {
													// console.log(error,body)
													var $ = cheerio.load(body);
													$('.re-num').html(parseInt($('.re-num').html())+1);
													if(!error && response.statusCode == 200) {
														fs.writeFile(path.join(path.resolve(__dirname, '../public/html/'),"ac" + param.id +'.html'),$.html(),function(err) {
															if(err) {
																console.log(err);
															}
															console.log('success:');
													    });
													}
												})
				if(result) {
					jsonWrite(res, {
						success: true,
						msg: '阅读加一'
					});
					conn.release();

				} else {
					jsonWrite(res, {
						success: false,
						msg: '添加失败'
					}, err);
				}
			});
		})

	},
	addPower: function(req, res, next) {
		var param = req.body;
		conn.getConnection(function(err, conn) {
			conn.query($sql.updatePower, [param.id], function(err, result) {
				if(result) {
                      						request('http://127.0.0.1:3000/html/ac'+parseInt(param.id)+'.html', function(error, response, body) {
													// console.log(error,body)
													var $ = cheerio.load(body);
													$('.power-span').html(parseInt($('.power-span').html())+1);
													if(!error && response.statusCode == 200) {
														fs.writeFile(path.join(path.resolve(__dirname, '../public/html/'),"ac" + param.id +'.html'),$.html(),function(err) {
															if(err) {
																console.log(err);
															}
															console.log('success:');
													    });
													}
												})
                      						
					jsonWrite(res, {
						success: true,
						msg: '点赞加一'
					});

				} else {
					jsonWrite(res, {
						success: false,
						msg: '添加失败'
					}, err);
				}
			});
		})

	},
	add: function(req, res, next) {
		var param = req.query || req.params;
		conn.getConnection(function(err, conn) {
			conn.query($sql.addInfo, ['0', '0', new Date()], function(err, result) {
				//console.log(param,param.number,new Date())
				if(result) {
					conn.query($sql.selectLast, {}, function(err, result) {
						//    console.log(result)
						jsonWrite(res, {
							success: true,
							msg: '主题添加成功',
							id: result[0].id
						});
						conn.release();
					})
				} else {
					jsonWrite(res, {
						success: false,
						msg: '添加失败'
					}, err);
				}
			});
		})

	},
	getList: function(req, res, next) {
		var param = req.query || req.params
		// conn.connect();
		//console.log(param.stauts)
		conn.getConnection(function(err, conn) {
			conn.query($sql.getList, [param.stauts], function(err, result) {
				// console.log(result)
				if(result) {
					jsonWrite(res, {
						success: true,
						msg: '列表获取成功',
						data: result
					});
					//   conn.end();
					conn.release();
				} else {
					jsonWrite(res, {
						success: false,
						msg: '列表获取失败'
					});
					// conn.end();
					conn.release();
				}
			});
		})
	},

	getInfo: function(req, res, next) {
		var param = req.query || req.params;
		//console.log(req.query,req.params,req.body )
		// conn.connect();
		conn.getConnection(function(err, conn) {
			conn.query($sql.getInfo, [param.id], function(err, result) {
				// console.log(result)
				if(result) {
					jsonWrite(res, {
						success: true,
						msg: '信息获取成功',
						data: result
					});
					//   conn.end();
					conn.release();
				} else {
					jsonWrite(res, {
						success: false,
						msg: '信息获取失败'
					});
					// conn.end();
					conn.release();
				}
			});
		})
	},
	updateInfo: function(req, res, next) {
		var param = req.body; //req.query || req.params||
		conn.getConnection(function(err, conn) {
			param.update = new Date()
			console.log(param.id)
			conn.query($sql.updateInfo, [param.title, param.content, new Date(), param.stauts, param.author, param.g_name, param.g_url, parseInt(param.review), parseInt(param.power), parseInt(param.id)], function(err, result) {
				//console.log(err)
				if(result) {
					if(param.stauts == '2') {
						console.log('------')
						//						request('http://127.0.0.1:3000/motion.html?id='+parseInt(param.id), function(error, response, body) {
						//							console.log(error,body)
						//							if(!error && response.statusCode == 200) {
						//								console.log(body) // Show the HTML for the baidu homepage. 
						//							}
						//						})
						let html = `
                        <!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <title>${param.title}</title>

</head>
<style>
    html{
        font-size: 20px;;
    }
    *{
        margin:0;
    }
    body{
       padding:1rem;
        font-size: .7rem;
        text-align: center;
    }
    .mo-body img{
        width:100%!important;
        margin:15px 0;
    }
    .af{
        float:left;
    }
    .afr{
        float:right;
    }
    .mo-header{

    }
    .mo-title{
        margin-bottom: 10px;
        line-height: 1.4;
        font-weight: 400;
        font-size: 24px;
    }
    .a-chacha,.a-chacha:hover,.a-chacha:active{
        text-decoration: none;
        color:#5ab0c9;
        font-size: 16px;
    }
    .mo-time{
        font-size: 16px;
        color:#8c8c8c;
    }
    .rich_media_meta_list{
        margin-bottom: 18px;
        line-height: 20px;
        font-size: 0;
    }
    * {
        margin: 0;
        padding: 0;
    }
    .tao-Div {
        background-color: #fbf9fd;
        padding: 0 1rem;
        padding-top: 3rem;
        text-align: center;
        margin-top: 1.5rem;
        margin-bottom: 20px;
        position: relative;
        padding-bottom: 20px;

    }

    .tao-Div p.text {
        margin-top: -5px;
        padding: 1.8rem .5rem;
        line-height: 1.6;
        text-align: center;
        color: #5ab0c9;
        background-color: #fff;
    }

    .tao-Div p.share_text {
        text-align: left;
        padding: 1rem;
        line-height: 1.6rem
    }
    .copy-all-text{
        padding: 5px;
        background-color: #5ab0c9;
        color: #fff;
        position: absolute;
        top: 2.5rem;
        left: 50%;
        transform: translate(-50%,-50%);
        z-index: 9;
    }
    .token-div .alert .bar {
        height: 75px;
        padding-top: 20px
    }

    .tao-Div .tip {
        padding: 1rem;
        margin: 0;
        color: #828888;
        text-align: left;
        background-color: #F6F7F6;
        line-height: 1.8rem
    }

    .tao-Div .msg {
        margin: 20px 0;
        color: #5ab0c9;
        text-align: left;
        line-height: 2rem
    }

    .tao-Div .btn {
        text-decoration: none;
        display: inline-block;
        width: 150px;
        margin: 0 3%;
        height: 30px;
        line-height: 30px;
        margin-top: 15px;
        color: #FFF;
        border-radius: 25px;
    }

    .tao-Div .btn.tpwd {
        background-color: #5ab0c9
    }

    .token-div .alert .btn.text {
        background-color: #5ab0c9
    }

    .tao-Div h2 {
        position: relative;
        height: 4.7rem;
        line-height: 4.7rem;
        color: #FFF;
        font-size: 1.6rem;
        text-align: center;
        background-color: #5ab0c9
    }

    .copy-text {
        user-select: auto;
        -webkit-user-select: auto;
        -moz-user-select: auto;
        -ms-user-select: auto
    }
    .weui-toast {
        position: fixed;
        z-index: 5000;
        width: 7.6em;
        min-height: 7.6em;
        top: 180px;
        left: 50%;
        margin-left: -3.8em;
        background: rgba(17, 17, 17, .7);
        text-align: center;
        border-radius: 5px;
        color: #FFF
    }

    .weui-icon_toast {
        margin: 22px 0 0;
        display: block
    }

    .weui-icon_toast.weui-icon-cancel:before, .weui-icon_toast.weui-icon-success-no-circle:before, .weui-icon_toast.weui-icon-warn:before {
        color: #FFF;
        font-size: 55px
    }

    .weui-icon_toast.weui-loading {
        margin: 30px 0 0;
        width: 38px;
        height: 38px;
        vertical-align: baseline
    }

    .weui-toast__content {
        margin: 0 0 15px
    }
    .content-div{
    	width:100%;
    	max-width: 750px;
    	margin-left:auto;
    	margin-right:auto;
    	text-align: left;
    }
</style>
<body>
	<div class="content-div">
<div class="mo-header" >
 <h2 class="mo-title">${param.title}</h2>
 <div class="rich_media_meta_list" style=""><span class="mo-time">${frm((new Date()).toString())}</span><span class="chachaname" style="font-size: 16px;color: #8c8c8c; margin: 0 10px;">${param.author}</span><a class="a-chacha" href="${param.g_url}">${param.g_name}</a></div>
</div>
<div class="weui-toast" id="J_FailToast" style="display:none">
    <i class="weui-icon-cancel weui-icon_toast"></i>
    <p class="weui-toast__content">复制失败</p>
</div>

<div class="weui-toast" id="J_SuccessToast" style="display:none">
    <i class="weui-icon-success-no-circle weui-icon_toast"></i>
    <p class="weui-toast__content">复制成功</p>
</div>
<div class="mo-body">
 ${param.content}
</div>
<div class="yd-div" style="color:#8c8c8c;margin-top: 20px;"><span class="review-span">阅读 <span class="re-num">${param.review}</span></span> <span class="add-num"><img style="width:20px;vertical-align: bottom;padding-left:10px;" src="/images/11.png"> <span class="power-span">${param.power}</span></span></div>
</div>
<script type="text/javascript" src="/javascripts/zepto.min.js"></script>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript" src="/javascripts/clipboard.min.js"></script>
<script>
    var timestamp,nonceStr,signature;
    var oldpower;
    wx.ready(function() {
        wx.onMenuShareAppMessage({
            title:$('.mo-title').html(), // 分享标题  .replace(/[^\u4e00-\u9fa5|,]+/,',')
            desc: removeHTMLTag($('.mo-body').html().toString()), // 分享描述
            link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: $('img').eq(0).attr('src'), // 分享图标
            type: '', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        wx.onMenuShareTimeline({
            title: $('.mo-title').html(), // 分享标题
            link: window.location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: $('img').eq(0).attr('src'), // 分享图标
            success: function () {
                // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
    })
    //var httpUrl='http://127.0.0.1:3000/';
    var httpUrl='/';
    oldpower = parseInt($('.add-num span').html())
    var showToast = function(toast) {
        toast.show();
        setTimeout(function() {
            toast.hide()
        }, 1000)
    }
    var successToast = $('#J_SuccessToast');
    var failToast = $('#J_FailToast');
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
    Zepto(function(){
        getmox()
        $('.add-num').on('click',function(){
        	if(parseInt(oldpower) == parseInt($('.add-num span').html())){
        		$('.add-num span').html(parseInt($('.add-num span').html())+1)
        		addPower(parseInt($('.add-num span').val())+1,${param.id})
        	} 
        	
        	
        })
        //console.log($('.j_CopyToken').size())

       addReview(parseInt($('.re-num').html()),${param.id})
    })
    function addReview(review,id){
    	$.ajax({
            url:httpUrl+'users/addReview',
            type:'post',
            data:{review:review,id:id},
            success:function(result){
                if(result){
                }
            }
       })
    }
    function addPower(power,id){
    	$.ajax({
            url:httpUrl+'users/addPower',
            type:'post',
            data:{power:power,id:id},
            success:function(result){
                if(result){
                }
            }
        })
    }
    
    function removeHTMLTag(str) {
        // str = str.replace(/<\/?[^>]*>/g,''); 

        str=str.replace(/&nbsp;/ig,'');
        str=str.replace(/\s/g,'');
        return str;
    }
    function getmox(){
        $.ajax({
            url:httpUrl+'users/getAllInfo',
            type:'get',
            data:{url:window.location.href},
            success:function(result){
                if(result){
                    // console.log(result)
                    // console.log(result)
                    timestamp=result.data.timestamp // 必填，生成签名的时间戳
                    nonceStr=result.data.nonceStr // 必填，生成签名的随机串
                    signature=result.data.signature

                    wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: 'wx4ea8199a93618609', // 必填，公众号的唯一标识
                        timestamp:timestamp, // 必填，生成签名的时间戳
                        nonceStr:nonceStr, // 必填，生成签名的随机串
                        signature: signature,// 必填，签名，见附录1
                        jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                    });
                }
            }
        })
    }
    function frm(str){
        span = Date.parse(str);
        dt = new Date(span);
        str = dt.getFullYear() + "-" + (dt.getMonth()+1) + "-" + dt.getDate();
        return str
    }
</script>
</body>

</html>

                        `

						// http.get('/motion.html?id='+ param.id, function(res) {
													fs.writeFile(path.join(path.resolve(__dirname, '../public/html/'),"ac" + param.id +'.html'),html,function(err) {
															if(err) {
																console.log(err);
															}
															console.log('success:');
													});

						// });
					}
					jsonWrite(res, {
						success: true,
						msg: '保存成功'
					});
					//   conn.end();
					conn.release();
				} else {
					jsonWrite(res, {
						success: false,
						msg: '保存失败'
					});
					// conn.end();
					conn.release();
				}
			});
		})
	},
	remove: function(req, res, next) {
		var param = req.body; //req.query || req.params||
		// console.log(req.query,req.params,req.body )
		// conn.connect();
		conn.getConnection(function(err, conn) {
			// param.update = new Date()
			// console.log(param)

			conn.query($sql.remove, [param.id], function(err, result) {
				//console.log(result)
				if(result) {
					jsonWrite(res, {
						success: true,
						msg: '删除成功'
					});
					//   conn.end();
					conn.release();
				} else {
					jsonWrite(res, {
						success: false,
						msg: '删除失败'
					});
					// conn.end();
					conn.release();
				}
			});
		})
	},
	intoPetData: function(req, res, next) {
		var param = req.query || req.params;

		// jsonWrite(res, {success: false, msg: '�û����Ѵ��ڣ�'});
		//conn.query($sql.intoPetData, [param.name], function(err, result) {
		//    console.log(result)
		//    if(result) {
		//        console.log('ͬ�����û��м���', result[0].account)
		//        if (result.length > 0) {
		//            jsonWrite(res, {success: false, msg: '�û����Ѵ��ڣ�'});
		//            // �ͷ�����
		//            conn.end();
		//        }else{
		//            conn.query($sql.register, [param.name, param.pas,new Date()], function(err, result) {
		//                if(result) {
		//                    result = {
		//                        success: true,
		//                        msg:'ע��ɹ�'
		//                    };
		//                }
		//
		//                // ��json��ʽ���Ѳ���������ظ�ǰ̨ҳ��
		//                jsonWrite(res, result);
		//
		//                // �ͷ�����
		//                conn.end();
		//            });
		//        }
		//    }
		//
		//    // ��json��ʽ���Ѳ���������ظ�ǰ̨ҳ��
		//
		//});
	},
	login: function(req, res, next) {
		var param = req.body || req.params
		// console.log(req.query,req.params,req.body )
		conn.getConnection(function(err, conn) {
			conn.query($sql.login, [param.loginName, param.password], function(err, result) {
				//   console.log(result)
				if(result.length > 0) {
					jsonWrite(res, {
						success: true,
						msg: '登录成功',
						data: result
					});
					conn.release();
				} else {
					jsonWrite(res, {
						success: false,
						msg: '用户名或密码错误！'
					});
					conn.release();
				}
			});
		})
	},
	register: function(req, res, next) {
		//  pool.getConnection(function(err, connection) {
		// ��ȡǰ̨ҳ�洫�����Ĳ���
		// console.log(res,next)
		var param = req.query || req.params;

		// �������ӣ�����в���ֵ

		conn.query($sql.selectUser, [param.name], function(err, result) {
			console.log(result)
			if(result) {
				console.log('ͬ�����û��м���', result[0].account)
				if(result.length > 0) {
					jsonWrite(res, {
						success: false,
						msg: '�û����Ѵ��ڣ�'
					});
					// �ͷ�����
					conn.end();
				} else {
					conn.query($sql.register, [param.name, param.pas, new Date()], function(err, result) {
						if(result) {
							result = {
								success: true,
								msg: 'ע��ɹ�'
							};
						}

						// ��json��ʽ���Ѳ���������ظ�ǰ̨ҳ��
						jsonWrite(res, result);

						// �ͷ�����
						conn.end();
					});
				}
			}

		});

	}
};
function frm(str){
        span = Date.parse(str);
        dt = new Date(span);
        str = dt.getFullYear() + "-" + (dt.getMonth()+1) + "-" + dt.getDate();
        return str
    }
function getDate(strDate) {
	var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/,
		function(a) {
			return parseInt(a, 10) - 1;
		}).match(/\d+/g) + ')');
	return date;
}